package org.example;

import org.example.utils.ListNode;

/**
 *
 */
public class AddTwoNumbers {

  public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dump = new ListNode(0);
    ListNode p = l1, q = l2, curr = dump;
    //进位
    int carry = 0;
    while (p != null && q != null) {
      int x = (p != null) ? p.val : 0;
      int y = (q != null) ? q.val : 0;
      int total = x + y + carry;
      //求除数
      carry = total / 10;
      //把余数设置在节点上
      curr.next = new ListNode(total % 10);
      curr = curr.next;
      if (p != null) {
        //取下一个节点的值
        p = p.next;
      }
      if (q != null) {
        q = q.next;
      }
    }
    //最有有余数 ，进位
    if (carry > 0) {
      curr.next = new ListNode(carry);
    }
    return dump.next;
  }


  public static void main(String[] args) {
    int[] arrays1 = new int[]{1, 4, 7, 2};
    int[] arrays2 = new int[]{2, 5, 1, 9};
    ListNode listNode1 = setValue(arrays1);
    ListNode listNod2 = setValue(arrays2);
    ListNode listNode = addTwoNumbers(listNode1, listNod2);

    while (listNode != null) {
      System.out.println(listNode.val);
      listNode = listNode.next;
    }
  }


  public static ListNode setValue(int[] arrays) {
    ListNode listNode = new ListNode(0);
    ListNode curr = listNode;
    for (int i = 0; i < arrays.length; i++) {
      curr.next = new ListNode(arrays[i]);
      curr = curr.next;
    }
    return listNode.next;
  }
}
